<?php
namespace app\index\controller;

use think\facade\View;
use think\worker\Server;
use think\facade\Session;
use GatewayClient\Gateway;

// require_once '../vendor/autoload.php';
// use app\index\model\Memberfriend;
// use app\index\model\Member;

class Worker extends Server{

    // json消息格式{
    //      type : say--发送的消息 bind--用户连接绑定client_id
    //      from : 谁发的
    //      to   : 给谁发的
    //      content : '发的内容'
    // }

    protected $socket = 'websocket://www.chat.com:2346';

    protected $client_id;

    public function onMessage($connection, $data)
    {
        $data = json_decode($data,true);
        if ($data["type"] == "say") {
            $result["type"] = "say";
            $result["from"] = $data["from"];
            $result["to"] = $data["to"];
            $result["content"] = $data["content"];
            dump($this->worker);
            $this->worker->clientIdConnections[$data["to"]]->send(json_encode($result,true));
        }
        // $json = [
        //     'type'  =>  'say',
        //     'from'  =>  '1615112847955',
        //     'to'    =>  $connection->client_id,
        //     'content' => $data["content"]
        // ];
        // $connection->send(json_encode($json,true));
    }

    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        // 生成一个唯一用户的客户端id
        $this->client_id = time().rand(100,999);
        // 将生成的client_id赋给当前连接
        $connection->client_id = $this->client_id;

        // 在当前worker对象中新添属性  保存当前登录的用户的client_id 和 连接对象
        // 以便进行推送
        $this->worker->clientIdConnections[$connection->client_id] = $connection;

        // 将生成的client_id发送给客户端
        $json = [
            'type'  =>  'bind',
            'from'  =>  'worker',
            'to'    =>  $connection->client_id,
            'content' => $this->client_id
        ];
        $connection->send(json_encode($json,true));
    }

    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        
    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {

    }
    
}